import sys
import time
import ok
import numpy
import pyqtgraph
import struct
from PyQt4 import QtGui, QtCore
from ui_main import *
from ui_setpoint import *

class MySetpoint(QtGui.QDialog, Ui_Setpoint):
    def __init__(self, parent=None):
        super(MySetpoint, self).__init__(parent)
        self.setupUi(self)
        self.setpoint = 2200
        self.old_setpoint = 2200
        self.label.setText(str(self.setpoint))
        self.horizontalSlider.setMinimum(2000)
        self.horizontalSlider.setMaximum(2400)
        self.horizontalSlider.setValue(2200)
        QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL('clicked()'), self.decrease)
        QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL('clicked()'), self.increase)
        QtCore.QObject.connect(self.horizontalSlider, QtCore.SIGNAL('valueChanged(int)'), self.movedSlider)

    def movedSlider(self,val):
        self.setpoint = val
        self.label.setText(str(self.setpoint))
        
    def decrease(self):
        self.setpoint -= 1
        self.label.setText(str(self.setpoint))
        self.horizontalSlider.setValue(self.setpoint)

    def increase(self):
        self.setpoint += 1
        self.label.setText(str(self.setpoint))
        self.horizontalSlider.setValue(self.setpoint)

    def accept(self):
        print 'accepted'
        xem.SetWireInValue(0x01,self.setpoint)
        xem.UpdateWireIns()
        self.old_setpoint = self.setpoint
        super(MySetpoint, self).accept()

    def reject(self):
        print 'rejected'
        self.setpoint = self.old_setpoint
        self.label.setText(str(self.setpoint))
        super(MySetpoint, self).accept()
        
class MyMainWindow(Ui_MainWindow):
    
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)
        self.wave1.setBackgroundRole(QtGui.QPalette.Base)
        self.wave1.setBackground(background=None)
        self.wave1.enableAutoRange('xy', False)
        self.wave1.setRange(xRange=(0,512),yRange=(-4000,4000),padding=0)
        self.wave2.setBackgroundRole(QtGui.QPalette.Base)
        self.wave2.setBackground(background=None)
        self.wave2.enableAutoRange('xy', False)
        self.wave2.setRange(xRange=(0,512),yRange=(-4000,4000),padding=0)
        self.wave3.setBackgroundRole(QtGui.QPalette.Base)
        self.wave3.setBackground(background=None)
        self.wave3.enableAutoRange('xy', False)
        self.wave3.setRange(xRange=(0,512),yRange=(-4000,4000),padding=0)
        self.mysetpoint = MySetpoint(self)
        QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL('toggled(bool)'), self.start)
        QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL('toggled(bool)'), self.dvr)
        QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL('toggled(bool)'), self.pause)
        QtCore.QObject.connect(self.pushButton_4, QtCore.SIGNAL('toggled(bool)'), self.record)
        QtCore.QObject.connect(self.pushButton_5, QtCore.SIGNAL('clicked()'), self.setpoint)
        QtCore.QObject.connect(self.pushButton_6, QtCore.SIGNAL('clicked()'), quit)

    def start(self,stat):
        global timer,ptr
        if(stat==True):
            self.plotVR = self.wave1.plot(pen=pyqtgraph.mkPen(color='r',width=3))
            self.plotVS = self.wave1.plot(pen=pyqtgraph.mkPen(color='y',width=3))
            self.plotVT = self.wave1.plot(pen=pyqtgraph.mkPen(color='b',width=3))
            self.plotCR = self.wave2.plot(pen=pyqtgraph.mkPen(color='r',width=3))
            self.plotCS = self.wave2.plot(pen=pyqtgraph.mkPen(color='y',width=3))
            self.plotCT = self.wave2.plot(pen=pyqtgraph.mkPen(color='b',width=3))
            self.plotLR = self.wave3.plot(pen=pyqtgraph.mkPen(color='r',width=3))
            self.plotLS = self.wave3.plot(pen=pyqtgraph.mkPen(color='y',width=3))
            self.plotLT = self.wave3.plot(pen=pyqtgraph.mkPen(color='b',width=3))
            #self.ptr = 0
            #self.plot1.setData(self.data1[ptr%10])
            #self.plot2.setData(self.data2[ptr%10])
            #self.plot3.setData(self.data3[ptr%10])
            #self.timer = QtCore.QTimer()
            #self.timer.timeout.connect(update)
            #QtCore.QObject.connect(self.timer, QtCore.SIGNAL('timeout()'), self.update)
            #self.timer.start(50)
            timer.start(20)
            #timer2.start(1000)
            self.pushButton.setText("Stop")
            self.pushButton_2.setEnabled(True)
            self.pushButton_3.setEnabled(True)
            self.pushButton_4.setEnabled(True)
            self.pushButton_5.setEnabled(True)
            self.pushButton_6.setEnabled(False)

        else:
            timer.stop()
            ptr = 0
            self.wave1.clear()
            self.wave2.clear()
            self.wave3.clear()
            self.pushButton.setText("Start")
            self.pushButton_2.setEnabled(False)
            self.pushButton_3.setEnabled(False)
            self.pushButton_4.setEnabled(False)
            self.pushButton_5.setEnabled(False)
            self.pushButton_6.setEnabled(True)
            self.pushButton_2.setChecked(False)
            self.pushButton_3.setChecked(False)
            self.pushButton_4.setChecked(False)
            xem.SetWireInValue(0x01,0)
            xem.UpdateWireIns()


    def dvr(self,stat):
        global timer,ptr
        if(stat==True):
            self.pushButton.setEnabled(False)
            self.pushButton_2.setText("Disable DVR")
            xem.SetWireInValue(0x00,1,0x01)
            xem.SetWireInValue(0x01,self.mysetpoint.setpoint)
            xem.UpdateWireIns()
        else:
            self.pushButton.setEnabled(True)
            self.pushButton_2.setText("Enable DVR")
            xem.SetWireInValue(0x00,0,0x01)
            xem.UpdateWireIns()

    def pause(self,stat):
        global timer
        if(stat==True):
            timer.stop()
            self.pushButton_3.setText("Resume")
        else:
            timer.start(20)

    def record(self,stat):
        global rec_stat, file
        if(stat==True):
            datetime = time.localtime()
            filename = time.strftime("record-%Y%m%d-%H%M%S", datetime)
            file = open('record/'+filename, 'w')
            file.write('test')
            rec_stat = 1
            self.pushButton_4.setText("Record ON")
        else:
            rec_stat = 0
            file.close()
            self.pushButton_4.setText("Record")

    def setpoint(self):
        print 'clicked'
        timer.stop()
        self.mysetpoint.exec_()
        timer.start(20)


def update():
    #global ptr,data1,data2,data3
    #timer.stop()

    arrayVR = []
    arrayVS = []
    arrayVT = []
    arrayCR = []
    arrayCS = []
    arrayCT = []
    arrayLR = []
    arrayLS = []
    arrayLT = []
    arrayTheta = []
    
    #print "Start Reading"
    xem.ReadFromBlockPipeOut(0xa0,20,buf)
    #print "Finish Reading"

    #print "start converting"
    for x in range(0, 512):
        VR = bytearray()
        VS = bytearray()
        VT = bytearray()
        CR = bytearray()
        CS = bytearray()
        CT = bytearray()
        LR = bytearray()
        LS = bytearray()
        LT = bytearray()
        theta = bytearray()

        theta.append(buf[(x*20)+19])
        theta.append(buf[(x*20)+18])
        intTheta = struct.unpack(">h", theta)
        arrayTheta.append(intTheta[0])

        if(rec_stat == 1):
            file.write(str(intTheta[0])+',')

        VR.append(buf[(x*20)+1])
        VR.append(buf[(x*20)+0])
        intVR = struct.unpack(">h", VR)
        arrayVR.append(intVR[0])

        if(rec_stat == 1):
            file.write(str(intVR[0])+',')

        VS.append(buf[(x*20)+3])
        VS.append(buf[(x*20)+2])
        intVS = struct.unpack(">h", VS)
        arrayVS.append(intVS[0])

        if(rec_stat == 1):
            file.write(str(intVS[0])+',')

        VT.append(buf[(x*20)+5])
        VT.append(buf[(x*20)+4])
        intVT = struct.unpack(">h", VT)
        arrayVT.append(intVT[0])

        if(rec_stat == 1):
            file.write(str(intVT[0])+',')

        CR.append(buf[(x*20)+7])
        CR.append(buf[(x*20)+6])
        intCR = struct.unpack(">h", CR)
        arrayCR.append(intCR[0])

        if(rec_stat == 1):
            file.write(str(intCR[0])+',')

        CS.append(buf[(x*20)+9])
        CS.append(buf[(x*20)+8])
        intCS = struct.unpack(">h", CS)
        arrayCS.append(intCS[0])

        if(rec_stat == 1):
            file.write(str(intCS[0])+',')

        CT.append(buf[(x*20)+11])
        CT.append(buf[(x*20)+10])
        intCT = struct.unpack(">h", CT)
        arrayCT.append(intCT[0])

        if(rec_stat == 1):
            file.write(str(intCT[0])+',')

        LR.append(buf[(x*20)+13])
        LR.append(buf[(x*20)+12])
        intLR = struct.unpack(">h", LR)
        arrayLR.append(intLR[0])

        if(rec_stat == 1):
            file.write(str(intLR[0])+',')

        LS.append(buf[(x*20)+15])
        LS.append(buf[(x*20)+14])
        intLS = struct.unpack(">h", LS)
        arrayLS.append(intLS[0])

        if(rec_stat == 1):
            file.write(str(intLS[0])+',')

        LT.append(buf[(x*20)+17])
        LT.append(buf[(x*20)+16])
        intLT = struct.unpack(">h", LT)
        arrayLT.append(intLT[0])

        if(rec_stat == 1):
            file.write(str(intLT[0])+'\n')

    #print "finish converting"

    #VRtuples = (arrayVR,arrayTheta)    
    #print VRtuples
    #for i in range(511):
    #    arrayVR[arrayTheta[i]]=arrayVR[i+1]

    #print i
    #print arrayVR[i+1]

    #arrayVR = [ arrayVR[i] for i in arrayTheta ]
    #arrayVS = [ arrayVS[i] for i in arrayTheta ]
    #arrayVT = [ arrayVT[i] for i in arrayTheta ]

    listTheta, listVR, listVS, listVT, listCR, listCS, listCT, listLR, listLS, listLT = zip(*sorted(zip(arrayTheta,arrayVR,arrayVS,arrayVT,arrayCR,arrayCS,arrayCT,arrayLR,arrayLS,arrayLT)))
    #print listVS
    #print "start plot"
    myapp.plotVR.setData(listVR)
    myapp.plotVS.setData(listVS)
    myapp.plotVT.setData(listVT)
    myapp.plotCR.setData(listCR)
    myapp.plotCS.setData(listCS)
    myapp.plotCT.setData(listCT)
    myapp.plotLR.setData(listLR)
    myapp.plotLS.setData(listLS)
    myapp.plotLT.setData(listLT)
    #print "finish plot"
    #print buf[0:20]
    #print arrayVR[:10]
    #print arrayVS[:10]
    #print arrayVT[:10]
    #print arrayTheta

    #data1 = numpy.random.normal(size=(10,512))
    #myapp.plot1.setData(data1[ptr%10])
    #data2 = numpy.random.normal(size=(10,512))
    #myapp.plot2.setData(data2[ptr%10])
    #data3 = numpy.random.normal(size=(10,512))    
    #myapp.plot3.setData(data3[ptr%10])
    #self.ptr += 1
    #plot1.setData(data1[ptr%10])
    #plot2.setData(data2[ptr%10])
    #plot3.setData(data3[ptr%10])

    xem.UpdateWireOuts()
    bufseq = xem.GetWireOutValue(0x20)
    #print bufseq
    if(bufseq == 0):
        myapp.label.setText("")
    else :
        myapp.label.setText("SAG")


def update2():
    localtime = time.localtime()
    timestring = time.strftime("%H:%M:%S", localtime)
    myapp.label2.setText(timestring)

app = QtGui.QApplication(sys.argv)

pyqtgraph.setConfigOption('background', None)

myapp = MyMainWindow()

xem = ok.FrontPanel()
xem.OpenBySerial(xem.GetDeviceListSerial(0))
xem.IsFrontPanelEnabled()

buf = bytearray("\x00"*10240)
bufseq = "\x00"  
rec_stat = 0
#plot1 = myapp.wave1.plot(pen='y')
#data1 = numpy.random.normal(size=(10,512))
#plot2 = myapp.wave2.plot(pen='y')
#data2 = numpy.random.normal(size=(10,512))
#plot3 = myapp.wave3.plot(pen='y')
#data3 = numpy.random.normal(size=(10,512))

#ptr = 0

timer = QtCore.QTimer()
timer.timeout.connect(update)
timer2 = QtCore.QTimer()
timer2.timeout.connect(update2)

timer2.start(1000)

file = 0
myapp.show()
sys.exit(app.exec_())

